package com.wujunshen.orika.convert;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.converter.BidirectionalConverter;
import ma.glasnost.orika.metadata.Type;

import java.io.IOException;

/**
 * User:  FrankWoo(吴峻申) <br>
 * Date:  2018/7/31 <br>
 * Time:  01:39 <br>
 * Email: frank_wjs@hotmail.com <br>
 */
public class JsonConvert<T> extends BidirectionalConverter<T, String> {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public String convertTo(T source, Type<String> destinationType, MappingContext mappingContext) {
        try {
            return OBJECT_MAPPER.writeValueAsString(source);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public T convertFrom(String source, Type<T> destinationType, MappingContext mappingContext) {
        try {
            return OBJECT_MAPPER.readValue(source, destinationType.getRawType());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}